define([
	"EasyUI",
	"EasyUI-lang",
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/combotree",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",        
    "Date", "DateCN", "css!DateCss",
], function (EasyUI, EasyUILang, Util, Tool, Combotree, SelectOrg, SearchBlock) { 
	$(document).ready(function (){
		var script   = document.createElement("script");
	    script.type  = "text/javascript";
	    script.src   = "/pcjd/static/app/detailview.js";
	    document.body.appendChild(script);
	})
    var getDivisionController = function () {
        return getServer() + "/platform/org/divisions/";
    };
    var getController = function () {
        return getServer() + "/pc";
    };
    var divisioncombotree // 行政区划组合树
    var menucombotree // 菜单组合树
    var selectedDivisions = [] // 组合树已选行政区划
    var selectedMenus = [] // 组合树已选的菜单
    
    // 初始化
    var init = function () {
	 	

        btnInit();
        createAuditGrid();
    }
 	// 表格輸入框
 	var obj = {}
 	//window.keyup = function(e) {
// 		console.log(e, $(e), $(e).val(), $(e).attr('data-divisionName'))
// 		var divisionCode = $(e).attr('data-divisionCode')
// 		var taskCode = $(e).attr('data-taskCode')
// 		var subkey = taskCode+"-"+divisionCode;
// 		var value = $(e).val()
//		obj[subkey] = value
 		//console.log(obj)
 		
 		//console.log(taskCode)
 	//}
 	window.checkNumberValue = function (inputObj) { 		
        //效验输入数字是否0-100
        if(!/(^0$)|(^100$)|(^\d{1,2}$)/.test(inputObj.value)) {
            if(inputObj.value>100){
                inputObj.value = 100;
            }
            if(inputObj.value<0){
                inputObj.value = 0;
            }
        }
        var divisionCode = $(inputObj).attr('data-divisionCode')
 		var taskCode = $(inputObj).attr('data-taskCode')
 		var subkey = taskCode+"-"+divisionCode;
 		var value = $(inputObj).val()
		obj[subkey] = value
    }

 	var createAuditGrid = function () {
 		$.ajax({
            url: getController() + "/getMenuInfo?taskCode=",
            // dataType: "application/json;charset=UTF-8",
            type: "get",
            success: function (res) {
            	var divisionColumns = res[0].divisionDataList.map(item => {
                    let obj = {
                        field: item.divisionCode,
                        title: item.divisionName,
                        width: "10%",
                        align: 'center',
//                      editor:{type:'numberbox',options:{precision:2}},
                        formatter: function (value, rowData, rowIndex) {

 							//console.log(rowData.level)
//							if(rowData.level = 2){
//								return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionName=${item.divisionName} value=${progressValue}>`
//							}
//							if(rowData.level = 0){
//								return 
//							}
							if(rowData.level == 1){
	                            let divisionDataList = rowData.divisionDataList
	                            let progressValue 
	                            divisionDataList.forEach(subitem => {
	                            	//debugger;
	                            	if(subitem.divisionCode == item.divisionCode){
	                            		progressValue = subitem.progressValue
	                            	}
	                                
	                            })		                        
		                        return progressValue
							}
							if(rowData.level == 2){
								let divisionDataList = rowData.divisionDataList
	                            let progressValue 
	                            divisionDataList.forEach(subitem => {
	                            	//debugger;
	                            	if(subitem.divisionCode == item.divisionCode){
	                            		progressValue = subitem.progressValue
	                            	}
	                                
	                            })		             
								return `<input type="number" class="form-control"  onchange="checkNumberValue(this)"  data-taskCode = ${rowData.taskCode} data-divisionCode=${item.divisionCode} value=${progressValue}>`
							}
	                       
	                        //
                        }
                    }
                    return obj
                })
            	$.ajax({
		            url: getController() + "/getMenuInfos",
		            // dataType: "application/json;charset=UTF-8",
		            type: "get",
		            success: function (res) {
		            	var datajson = [];
		            	datajson.push(res);
		            	//console.log(datajson)
    					$("#auditGrid").treegrid({
				            //url: getController() + "/getMenuInfos",
				            //method:"GET",				            
				            //fit: true,
				            fitColumns: true,
				            autoRowHeight: false,
				            nowrap: false,
				            idField: 'taskCode',
				            treeField: 'taskName',
							frozenColumns: [[
				                {
				                    field: 'taskName',
				                    title: '任务名称',
				                    width: '40%',
				                    
				                }
					        ]],
				            columns: [
				                [
				                ...divisionColumns
				                ]
				            ],
				           	data:datajson,
				            onLoadSuccess: function (data) {
				            	$(".tree-icon,.tree-file").removeClass("tree-icon tree-file");
				        		$(".tree-icon,.tree-folder").removeClass("tree-icon tree-folder tree-folder-open tree-folder-closed"); 
				                // console.log(data)
				            },
				            // pagination: true,
				            // pageSize: 10
				        });
		            }
            	})
            	

            	
            	
            }
        })
 	}
//  var createAuditGrid = function () {
//  	$.ajax({
//          url: getController() + "/getMenuInfo?taskCode=",
//          // dataType: "application/json;charset=UTF-8",
//          type: "get",
//          success: function (res) {
//          	//console.log(res)
//          	var columns = res[0].divisionDataList.map(item => {
//                  let obj = {
//                      field: item.divisionCode,
//                      title: item.divisionName,
//                      width: 150,
//                      align: 'center',
////                      editor:{type:'numberbox',options:{precision:2}},
//                      formatter: function (value, rowData, rowIndex) {
////                          let divisionDataList = rowData.divisionDataList
////                          let progressValue 
////                          divisionDataList.forEach(item => {
////                              progressValue = item.progressValue
////                          })
//	                        
//	                        return item.progressValue
//	                        //return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionName=${item.divisionName} value=${progressValue}>`
//                      }
//                  }
//                  return obj
//              })
//          	//console.log(columns)
//          	var subcolumns = res[0].divisionDataList.map(item => {
//                  let obj = {
//                      field: item.divisionCode,
//                      title: item.divisionName,
//                      width: 150,
//                      align: 'center',
////                      editor:{type:'numberbox',options:{precision:2}},
//                      formatter: function (value, rowData, rowIndex) {
//                      	let divisionDataList = rowData.divisionDataList
//                          let progressValue 
//                          divisionDataList.forEach(subitem => {
//                          	//debugger;
//                          	if(subitem.divisionCode == item.divisionCode){
//                          		progressValue = subitem.progressValue
//                          	}
//                              
//                          })
//	                        
//	                        return progressValue
//	                        //return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionCode=${item.divisionCode} value=${progressValue}>`
//                      }
//                  }
//                  return obj
//              })
//          	//console.log(subcolumns)
//          	var ssubcolumns = res[0].divisionDataList.map(item => {
//                  let obj = {
//                      field: item.divisionCode,
//                      title: item.divisionName,
//                      width: 150,
//                      align: 'center',
////                      editor : {
////                      	type: 'numberbox',
////                  	},
//                      formatter: function (value, rowData, rowIndex) {
//                          let divisionDataList = rowData.divisionDataList
//                          let progressValue 
//                          divisionDataList.forEach(subitem => {
//                              if(subitem.divisionCode == item.divisionCode){
//                          		progressValue = subitem.progressValue
//                          	}
//                          })
////	                        debugger;
////	                        console.log(rowData.taskCode)
//	                        // return progressValue
//	                        return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionCode=${item.divisionCode} value=${progressValue}>`
//                      }
//                  }
//                  return obj
//              })
//  			$('#dg').datagrid({
//  				view: detailview,
//		            url:getController() + "/getMenuInfo?taskCode=",
//		            method:"GET",
//		            singleSelect: true,
//		            fitColumns:false,
//		            rownumbers: false,
//		            resizable: false,
//		            fixed: true,
//		            nowrap: true,
//		            striped: true, //条纹
//		            width: "100%",
//		            height: "auto",            
//		            showFooter:true, 
////		            frozenColumns: [[
////	                    {
////		                    field: 'taskName',
////		                    title: '任务名称',
////		                    align: 'left',
////		                    width: 250,
////		                },
////			        ]],
//		            columns: [
//		                [
//		                	//{field: '_id',title: 'ex',width:'10%',expander: true,hidden:true},//隐藏默认+-按钮
//		                	{
//			                    field: 'taskName',
//			                    title: '任务名称',
//			                    align: 'left',
//			                    width: 250,
//			                },
//		                	...columns
//		                ]
//		            ],		            
//					detailFormatter: function(value, rows){
//						return  '<div style="padding:0px"><table class="ddv"></table></div>';		
//					},
//					onExpandRow: function(index,row){
//						var ddv = $(this).datagrid('getRowDetail',index).find('table.ddv');
//						ddv.datagrid({
//							view: detailview,
//							url:getController() + "/getMenuInfo?taskCode="+row.taskCode,
//							method:"GET",
//							showHeader:false,
//							fitColumns:false,
//							singleSelect:true,
//							rownumbers:false,
//							height:'auto',
////							frozenColumns: [[
////			                    {
////				                    field: 'taskName',
////				                    title: '任务名称',
////				                    align: 'left',
////				                    width: 222,
////			                	},
////					        ]],
//							columns:[
//								[
//								{
//				                    field: 'taskName',
//				                    align: 'left',
//				                    width: 222,
//			                	},
//			                	...subcolumns
//								]
//							],				            
//							detailFormatter: function(value, rows){
//								return  '<div style="padding:0px"><table class="dddv"></table></div>';		
//							},
//							onExpandRow: function(index,row){
//								var dddv = $(this).datagrid('getRowDetail',index).find('table.dddv');
//								dddv.datagrid({
//									url:getController() + "/getMenuInfo?taskCode="+row.taskCode,
//									method:"GET",
//									showHeader:false,
//									fitColumns:false,
//									nowrap: false,
//									singleSelect:true,
//									rownumbers:false,
//									height:'auto',
////									frozenColumns: [[
////					                    {
////						                    field: 'taskName',
////						                    title: '任务名称',
////						                    align: 'center',
////						                    width: 219,
////					                	},
////							        ]],
//									columns:[
//										[
//										{
//						                    field: 'taskName',
//						                    title: '任务名称',
//						                    align: 'center',
//						                    width: 219,
//					                	},
//					                	...ssubcolumns
//										]
//									],
//									onLoad:function(){
//					                        ddv.datagrid('fixDetailRowHeight',index);
//					                        ddv.datagrid('selectRow',index);
//					                        ddv.datagrid('getRowDetail',index).find('form').form('load',row);
//					                        ddv.datagrid('fixDetailRowHeight',index);
//					                        ddv.datagrid('fixRowHeight', index);  
//					                    },
//									onResize:function(){
//										ddv.datagrid('fixDetailRowHeight',index);
//									},
//									onLoadSuccess:function(){
//										var rows = dddv.datagrid('getRows');
//						                for ( var i = 0; i < rows.length; i++) {
//						                    dddv.datagrid('beginEdit', i);
//						                }
//										setTimeout(function(){
//											ddv.datagrid('fixDetailRowHeight',index);
//											ddv.datagrid('fixRowHeight',index);//防止出现滑动条 
//										},0);
//									}
//								});
//							},
//							onLoad:function(){
//			                        $('#dg').datagrid('fixDetailRowHeight',index);
//			                        $('#dg').datagrid('selectRow',index);
//			                        $('#dg').datagrid('getRowDetail',index).find('form').form('load',row);
//			                        $('#dg').datagrid('fixDetailRowHeight',index);
//			                        $('#dg').datagrid('fixRowHeight', index);  
//			                    },
//							onResize:function(){
//								$('#dg').datagrid('fixDetailRowHeight',index);
//							},
//							onLoadSuccess:function(){
////								var rows = ddv.datagrid('getRows');
////				                for ( var i = 0; i < rows.length; i++) {
////				                    ddv.datagrid('beginEdit', i);
////				                }
//								setTimeout(function(){
//									$('#dg').datagrid('fixDetailRowHeight',index);
//									$('#dg').datagrid('fixRowHeight',index);//防止出现滑动条 
//								},0);
//							}
//						});
//						$('#dg').datagrid('fixDetailRowHeight',index);
//					},
//		        });
//          }
//      })
//
//	};
    // 初始化按钮 保存
    var btnInit = function () {
        $('#saveBtn').on('click', function () {
        	debugger;
        	var params = [];
        	for(let objkey in obj){
			    //console.log(objkey+"----->"+obj[objkey]);
			    // id----->1
				// name----->apple
				// price----->4
				var newobj = {
					"taskCode": objkey.split("-")[0],
			      	"divisionCode": objkey.split("-")[1],
			      	"progressValue": obj[objkey]
				}
				params.push(newobj)
			}
	 		//console.log(params)
//			var rows = $("#dg").datagrid('getRows');
////          for ( var i = 0; i < rows.length; i++) {
////              $("#dg").datagrid('endEdit', i);
////          }
//
//          var metaColumns = $("#dg").datagrid('getChanges');
////          for ( var i = 0; i < rows.length; i++) {
////              $("#dg").datagrid('beginEdit', i);
////          }
            $.ajax({
                type: "post",
                url: getController()+ '/update',
                contentType: "application/json",
                data: JSON.stringify(params),
                success: function(res){
                    //保存成功后重新获取表信息
                    obj = {};
                    //console.log(res)
                    Util.alert(res.message);
                    createAuditGrid();
                    
                }
            });


        })
        
    }
    // 用过菜单ID找菜单名称 @menuId
    var getMenuNameById = function (id) {
        return Menu.filter(item => {
            return item.menuId == id
        })
    }
    // 导出
    var exportProject = function () {
        // 把已选择的行政区划的divisionCode作为参数
        var divisions = selectedDivisions.map(item => {
            return item.divisionCode
        }).toString()
        // 把已选择的菜单类型的menuId 作为参数
        var menuIds = selectedMenus.map(item => {
            return item.menuId
        }).toString()
        var params = {
            startTime: $('#dt1').datebox('getValue'),
            endTime: $('#dt2').datebox('getValue'),
            dataType: $('#dataType').val() || '0',
            divisions,
            menuIds,
            type: $('#type').val(),
        }
        // $.ajax({
        //     url: getController() + "/isEmpty",
        //     data: params,
        //     type: "get",
        //     success: function (data) {
        //         // console.log(data);
        //         if (data.message == '否') {
        //             window.location.href = getController() + "/export?startTime=" + (params.startTime || '') + "&endTime=" + (params.endTime || '') + "&dataType=" + (params.dataType || '') + "&divisions=" + (params.divisions || '') + "&menuIds=" + (params.menuIds || '') + "&type=" + (params.type || '');
        //         } else if (data.message == '是') {
        //             Util.alert('该类型数据数据为空，无法导出！');
        //         } else {
        //             // 未选择类型，请选择一种类型！
        //             Util.alert(data.message);
        //         }
        //     }
        // });
        window.location.href = getController() + "/export?startTime=" + (params.startTime || '') + "&endTime=" + (params.endTime || '') + "&dataType=" + (params.dataType || '') + "&divisions=" + (params.divisions || '') + "&menuIds=" + (params.menuIds || '') + "&type=" + (params.type || '');
    }
    return {
        init:init
    }
})